from django.shortcuts import render

# Create your views here.
from django.views import View
from apps.areas.models import Area
from django.http import JsonResponse
from django.core.cache import cache


class ProvinceView(View):
    def get(self, request):
        # 先读取缓存
        data_list = cache.get('province')

        # 1. 查询省份信息
        province = Area.objects.filter(parent__isnull=True)

        data_list = []
        # 2. 将省份查询结果集 转换为 字典列表
        for area in province:
            data_list.append({
                'id': area.id,
                'name': area.name
            })
        # 这里缓存
        # cache.set(key,value,seconds)
        # 过期时长 要结合具体的需求
        cache.set('province', data_list, 24 * 3600)
        # 3. 返回响应
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'province_list': data_list})


class SubAreaView(View):

    def get(self, request, parent_id):
        # 1.获取 省[市] 的id

        # 读取缓存
        data_list = cache.get('city_%s' % parent_id)

        if data_list is None:
            # 2. 根据 省[市] 的id 获取下一级数据
            # 方式1:
            # areas = Area.objects.filter(parent=parent_id)
            # 方式2
            # ① 根据 parent_id 获取 省 [市]
            pro_city_id = Area.objects.get(id=parent_id)
            # areas = pro_city_id.area_set.all()
            areas = pro_city_id.subs.all()
            data_list = []
            # 3. 将查询结果集遍历转换为字典列表
            for area in areas:
                data_list.append({
                    'id': area.id,
                    'name': area.name
                })

            # 设置缓存
            cache.set('city_%s' % parent_id, data_list, 24 * 3600)

        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'sub_data': {
                                 'subs': data_list
                             }
                             })

# class SubAreaView(View):
#
#     def get(self,request,parent_id):
#
#         subs_list = cache.get('city_%s'%parent_id)
#
#         if subs_list is None:
#
#             # 1.获取 省[市] 的id
#             # 2. 根据 省[市] 的id 获取下一级数据
#             #方式1
#             # areas = Area.objects.filter(parent_id=parent_id)
#             # 方式2
#             # ① 根据 parent_id 获取 省 [市]
#             pro_city_id = Area.objects.get(id=parent_id)
#             # areas = pro_city_id.area_set.all()
#             areas = pro_city_id.subs.all()
#
#             subs_list = []
#             # 3. 将查询结果集遍历转换为字典列表
#             for area in areas:
#                 subs_list.append({
#                     'id':area.id,
#                     'name':area.name
#                 })
#
#             cache.set('city_%s'%parent_id,subs_list,24*3600)
#         # 4. 返回响应
#         return JsonResponse({
#             "code": "0",
#             "errmsg": "OK",
#             "sub_data": {
#                 "subs": subs_list
#             }
#         })
